#pragma once

#include <string>
#include <memory>
#include "media_frame.h"

extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/avutil.h>
}

namespace El {
namespace Muxer {

class MP4Writer {
public:
    MP4Writer();
    ~MP4Writer();

    void SetVideoParams(int width, int height, int fps);

    void SetAudioParams(int sampleRate, int channels, int depth);

    bool Open(const std::string &filePath);

    bool WriteFrame(const Media::MediaFramePtr &frame);

    void Close();

    /// @brief 获取文件时长
    /// @return 文件时长，单位：秒
    uint64_t GetDuration() const;

    /// @brief 获取文件大小
    /// @return 文件大小，单位：字节
    uint64_t GetFileSize() const;

private:
    // 禁止拷贝和赋值
    MP4Writer(const MP4Writer &) = delete;
    MP4Writer &operator=(const MP4Writer &) = delete;

    // 内部初始化函数
    bool InitializeStreams();
    bool WriteVideoFrame(const Media::MediaFramePtr &frame);
    bool WriteAudioFrame(const Media::MediaFramePtr &frame);

    bool IsOpened() const
    {
        return formatContext_ != nullptr;
    }

    // 文件相关
    std::string filePath_;
    AVFormatContext *formatContext_{nullptr};

    // 流相关
    AVStream *videoStream_{nullptr};
    AVStream *audioStream_{nullptr};

    // 状态标记
    int64_t videoStartTime_{-1};
    int64_t audioStartTime_{-1};
    bool isInitialized_{false};

    // 参数配置
    struct VideoParams {
        int width{0};
        int height{0};
        int fps{0};
    } videoParams_;

    struct AudioParams {
        int sampleRate{0};
        int channels{0};
        int depth{0};
    } audioParams_;

    int64_t lastVideoDts_{-1}; // 上一个视频帧的 DTS
    int64_t lastAudioDts_{-1}; // 上一个音频帧的 DTS

    bool hasFirstIFrame_{false};
};

} // namespace Muxer
} // namespace El